package com.dreamer.view.lottery;

import com.dreamer.domain.lottery.Lottery;
import com.dreamer.service.lottery.LotteryHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import ps.mx.otter.utils.message.Message;

import java.util.Optional;

@Controller
@RequestMapping("/lottery")
public class LotteryController {

    @Autowired
    private LotteryHandler lotteryHandler;

    @RequestMapping(value = "/edit.json", method = RequestMethod.POST)
    public Message edit(@ModelAttribute("parameter") Lottery lottery) {
        try {
            lotteryHandler.saveOrUpdate(lottery);
            return Message.createSuccessMessage();
        } catch (Exception exp) {
            exp.printStackTrace();
            return Message.createFailedMessage();
        }
    }

    @RequestMapping(value = "/remove.json", method = RequestMethod.DELETE)
    public Message remove(@ModelAttribute("parameter") Lottery lottery) {
        try {
            lotteryHandler.removeActivity(lottery);
            return Message.createSuccessMessage();
        } catch (Exception exp) {
            exp.printStackTrace();
            return Message.createFailedMessage();
        }
    }

    @ModelAttribute("parameter")
    public Lottery preprocess(@RequestParam("id") Optional<Integer> id) {
        Lottery lottery = new Lottery();
        if (id.isPresent()) {
            lottery = lotteryHandler.findById(id.get());
        }
        return lottery;
    }

}
